package com.rlz.base.base

import com.rlz.base.tools.refresh.RefreshLayout

/**
 * Created by RLZ
 * on 2021/7/2
 *
 * 用来 拓展LiveData
 *
 */
class Resource<T> {

    var mState: Int
    var errorMsg: String? = null
    var data: T? = null
    var error: Throwable? = null

    constructor(state: Int, data: T?, errorMsg: String?) {
        mState = state
        this.errorMsg = errorMsg
        this.data = data
    }

    constructor(state: Int, error: Throwable?) {
        mState = state
        this.error = error
    }

    fun handler(callback: OnHandleCallback<T?>) {
        when (mState) {
            LOADING -> callback.onLoading(errorMsg)
            SUCCESS -> callback.onSuccess(data)
            FAIL -> callback.onFailure(errorMsg)
            ERROR -> callback.onError(error)
        }

        if (mState != LOADING) callback.onCompleted()
    }

    fun handler(callback: OnHandleCallback<T?>, refreshLayout: RefreshLayout) {
        when (mState) {
            LOADING -> callback.onLoading(errorMsg)
            SUCCESS -> {
                callback.onSuccess(data)
                refreshLayout.finishRefreshing()
                refreshLayout.finishLoadmore()
            }
            FAIL -> {
                callback.onFailure(errorMsg)
                refreshLayout.finishRefreshing()
                refreshLayout.finishLoadmore()
            }
            ERROR -> {
                callback.onError(error)
                refreshLayout.finishRefreshing()
                refreshLayout.finishLoadmore()
            }
        }
        if (mState != LOADING) {
            callback.onCompleted()
        }
    }

    interface OnHandleCallback<T> {

        fun onLoading(showMessage: String?)

        fun onSuccess(data: T)

        fun onFailure(msg: String?)

        fun onError(error: Throwable?)

        fun onCompleted()
    }

    companion object {
        /**
         * 请求的状态:
         *
         * 0表示加载中；
         *
         * 1表示成功；
         *
         * 2表示联网失败；
         *
         * 3表示接口虽然走通，但走的失败
         */
        const val LOADING = 0

        const val SUCCESS = 1

        const val ERROR = 2

        const val FAIL = 3

        @JvmStatic
        fun <T> loading(showMsg: String?): Resource<T?> = Resource(LOADING, null, showMsg)

        @JvmStatic
        fun <T> success(data: T): Resource<T> = Resource(SUCCESS, data, null)


        @JvmStatic
        fun <T> failure(msg: String?): Resource<T?> = Resource(ERROR, null, msg)

        @JvmStatic
        fun <T> error(t: Throwable?): Resource<T> = Resource(ERROR, t)

        @JvmStatic
        fun <T> response(data: BaseResponse<T>?): Any {
            return if (data != null) {
                if (data.isSuccess()) {
                    Resource(SUCCESS, data.getData(), null)
                } else Resource(FAIL, null, data.getErrorMsg())
            } else Resource(ERROR, null, null)
        }
    }
}